import React,{useState} from 'react';
import axios from 'axios';
import md5 from 'md5-node';
import { Form, Input, Button, Checkbox, message } from 'antd';
import './LoginRegister.less';
// 密匙工具库
import {userSecretToken} from '../../assets/tools/create-secret-token';

function Login(props) {
    const secretID = localStorage.getItem('secretID');
    let isChecked = false;
    let defaultUserName = '';
    let defaultUserPassword = '';
    // 如果存在
    if(secretID) {
        // 解码账号和密码
        const userSecretInfo = secretID.split(userSecretToken);
        // 赋值给原始账号密码值
        defaultUserName = window.atob(userSecretInfo[0]);
        defaultUserPassword = window.atob(userSecretInfo[1]);
        // 选中记住密码框
        isChecked = true;
    }
    // 用户名
    const [username] = useState(defaultUserName);
    // 密码
    const [userpassword] = useState(defaultUserPassword);
    // 记住密码
    const [rememberUser] = useState(isChecked);

    /**
     * 登录正常的回调
     * @param {Object} values 表单输入的值
     */
    const onFinish = (values) => {
        // 密码MD5字符串加密
        const userpassword = md5(values.userpassword);
        // 组成用户登录信息对象
        const userLoginInfo = {
            username: values.username,
            userpassword,
            remember: values.remember
        }

        // 向服务器发送登录请求数据
        axios.post(
                '/api/userinfo/user_login',
                userLoginInfo
            )
            // 请求成功
            .then(res => {
                // 服务器返回结果
                const resObj = res.data;
                // 如果没有查询到用户
                if(resObj.result === 'Fail') {
                    message.error({
                        content: '账号或密码错误！',
                        className: 'message-box'
                    });
                }
                // 查询到对应用户
                else {
                    // 将用户 session 进行浏览器会话存储
                    sessionStorage.setItem('sessionInfo', resObj.session_info);
                    message.success({
                        content: '登录成功！',
                        style: {
                            marginTop: '20vh'
                        }
                    });
                    // 设置用户名Session
                    sessionStorage.setItem('username', userLoginInfo.username);
                    // 是否记住账号密码
                    if(userLoginInfo.remember) {
                        // 设置密匙
                        localStorage.setItem('secretID', `${window.btoa(userLoginInfo.username).replace(/=/g, '')}${userSecretToken}${window.btoa(values.userpassword).replace(/=/g, '')}`);
                    }
                    // 不记住账号
                    else {
                        if(localStorage.getItem('secretID')) {
                            localStorage.removeItem('secretID');
                        }
                    }
                    // 设置登录状态
                    props.setLoginState();
                }
                
            })
            // 请求异常
            .catch(err => {
                message.error({
                    content: '网络或服务器发生异常！',
                    className: 'message-box'
                });
                console.error(err)
            });
    };

    /**
     * 登录出现错误的时候的回调
     * @param {String} errorInfo 错误信息
     */
    const onFinishFailed = (errorInfo) => {
        message.error({
            content: '网络或服务器发生异常！',
            className: 'message-box'
        });
    };

    return (
        <div className="login-register-box">
            <Form
                id="userLoginForm"
                name="userLoginForm"
                method="POST"
                labelCol={{ span: 6, }}
                wrapperCol={{ span: 18, }}
                initialValues={{
                    username: username,
                    userpassword: userpassword,
                    remember: rememberUser,
                }}
                onFinish={onFinish}
                onFinishFailed={onFinishFailed}
                autoComplete="off"
                size="large"
            >
                <h2>用户登录</h2>
                <Form.Item
                    label="账号"
                    name="username"
                    rules={[{
                        required: true,
                        message: '请输入您的账号',
                    }]}
                >
                    <Input />
                </Form.Item>

                <Form.Item
                    label="密码"
                    name="userpassword"
                    rules={[{
                        required: true,
                        message: '请输入您的密码',
                    }]}
                >
                    <Input.Password />
                </Form.Item>

                <Form.Item
                    name="remember"
                    valuePropName="checked"
                    wrapperCol={{
                        offset: 6,
                        span: 8,
                    }}
                    style={{marginBottom: '10px'}}
                >
                    <Checkbox>记住账号</Checkbox>
                </Form.Item>

                <Form.Item
                wrapperCol={{
                    offset: 6,
                    span: 18,
                }}
                >
                    <Button type="primary" htmlType="submit">
                        登录
                    </Button>
                    <span className="switch-sign-in-up" span={10}>去注册一个账号</span>
                </Form.Item>
            </Form>
        </div>
    );
}

export default Login;
